import * as maptilersdk from '@maptiler/sdk';

/**
 * 地图控件容器管理器，实现 IControl 接口
 * 只负责创建和管理 DOM 容器，不涉及 React 渲染
 * 真正的 React 组件通过 Portal 渲染到这个容器中
 */
export class MapControlContainer implements maptilersdk.IControl {
  private container: HTMLDivElement | null = null;
  private position: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';

  constructor(position: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' = 'top-right') {
    this.position = position;
  }

  onAdd(map: maptilersdk.Map): HTMLElement {
    // 创建容器 DOM
    this.container = document.createElement('div');
    this.container.className = 'maplibregl-ctrl';
    
    // 阻止地图事件冒泡
    this.container.addEventListener('mousedown', (e) => e.stopPropagation());
    this.container.addEventListener('touchstart', (e) => e.stopPropagation());
    this.container.addEventListener('dblclick', (e) => e.stopPropagation());
    this.container.addEventListener('wheel', (e) => e.stopPropagation());

    return this.container;
  }

  onRemove(): void {
    if (this.container && this.container.parentNode) {
      this.container.parentNode.removeChild(this.container);
    }
    this.container = null;
  }

  getDefaultPosition(): string {
    return this.position;
  }

  // 获取容器元素，供 Portal 使用
  getContainer(): HTMLElement | null {
    return this.container;
  }
}